﻿using B.S.Sell.Domain;
using B.S.Sell.ErrorCode;
using B.S.Sell.Read.API.Application.Command123.ProductNameCommand;
using B.S.Sell.Read.API.Application.Command123.PurNameCommand;
using B.S.Sell.Read.API.Dtos;
using DAL;
using MediatR;

namespace B.S.Sell.Read.API.Application.Commandhander123
{

    public class GetProductNameCommandHander : IRequestHandler<GetProductNameCommand, ApiResult<Apipage<SellModel>>>
    {
        public readonly DBHelper1 dBHelper;

        public GetProductNameCommandHander(DBHelper1 dBHelper)
        {
            this.dBHelper = dBHelper;
        }

        public Task<ApiResult<Apipage<SellModel>>> Handle(GetProductNameCommand request, CancellationToken cancellationToken)
        {
            ApiResult<Apipage<SellModel>> apiResult = new ApiResult<Apipage<SellModel>>();
            apiResult.Code = (ApiEnums)Renum.显示成功;
            apiResult.Message = Renum.显示成功.ToString();

            try
            {
                string baseListSql = "SELECT count(*) FROM ProductModel";
                string baseSql = "SELECT * FROM ProductModel";

                List<string> conditions = new List<string>();

                // 新增 WHouseId 查询条件（int类型）
                //if (request.WHouseId != null)
                //{
                //    conditions.Add($"B.WHouseId = {request.WHouseId}");
                //}

                //if (!string.IsNullOrEmpty(request.WarehouseName))
                //{
                //    conditions.Add($"B.WarehouseName LIKE '%{request.WarehouseName}%'");
                //}
                //if (!string.IsNullOrEmpty(request.WarehouseNumber))
                //{
                //    conditions.Add($"B.WarehouseNumber LIKE '%{request.WarehouseNumber}%'");
                //}

                //string conditionString = string.Join(" AND ", conditions);
                //if (!string.IsNullOrEmpty(conditionString))
                //{
                //    baseListSql += " AND " + conditionString;
                //    baseSql += " AND " + conditionString;
                //}
                string list = baseListSql;
                string sql = $"{baseSql} ORDER BY InternalCode OFFSET (({request.PageIndex} - 1) * {request.PageSize}) ROWS FETCH NEXT {request.PageSize} ROWS ONLY";

                Apipage<SellModel> apipage = new Apipage<SellModel>();
                apipage.TotalCount = (int)dBHelper.Scalar(list);
                apipage.PageCount = (int)Math.Ceiling(apipage.TotalCount * 1.0 / request.PageSize);
                apipage.List = dBHelper.GetList<SellModel>(sql);
                apiResult.Data = apipage;
            }
            catch (Exception ex)
            {
                apiResult.Code = (ApiEnums)Renum.显示失败;
                apiResult.Message = $"查询数据时发生错误: {ex.Message}";
                apiResult.Data = new Apipage<SellModel>();
            }

            return Task.FromResult(apiResult);
        }
    }
}
